package com.xx.job.controller.util;


import com.xx.job.common.Result;
import com.xx.job.controller.base.BaseController;
import com.xx.job.entity.system.SysFileInfo;
import com.xx.job.service.system.SysFileInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

/**
 * 文件上传
 */
@RestController
@RequestMapping("/api/v1/public")
public class FileController  extends BaseController {

    @Autowired
    private SysFileInfoService sysFileInfoService;


    @PostMapping(value = "/uploadFile")
    public Result fileUpload(@RequestParam(value = "file") List<MultipartFile> files,String type, HttpServletRequest request) {
        MultipartFile file = null;
        List<Map<String,Object>> list = new ArrayList<>();
        for (int i = 0; i < files.size(); i++) {
            file = files.get(i);
            if (file.isEmpty()) {
                System.out.println("文件为空");
            }
            String fileName = file.getOriginalFilename();  // 文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
            String filePath = "D://temp-rainy//"; // 上传后的路径
            String newFileName = UUID.randomUUID() + suffixName; // 新文件名
            long size = file.getSize(); //文件大小
            File dest = new File(filePath + newFileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String path = "/temp-rainy/" + fileName;
            // 文件信息
            StringBuffer url = request.getRequestURL();
            String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
            String full_path = tempContextUrl + "api/v1/public/download/" + newFileName;
            Map<String,Object> data = new HashMap<>();
            data.put("type",type);
            data.put("name",fileName);
            data.put("size",size);
            data.put("path",newFileName);
            data.put("full_path",full_path);
            list.add(data);
        }
        return Result.success(list);
    }

    @GetMapping("/download/{path}")
    public ResponseEntity<InputStreamResource> downloadFile(@PathVariable String path)
            throws IOException {
        SysFileInfo sysFileInfo = sysFileInfoService.selectBy(path);


        String filePath = "D:/temp-rainy/"+path;
        FileSystemResource file = new FileSystemResource(filePath);
        String fileName= file.getFilename();
        if(sysFileInfo != null && StringUtils.isNotBlank(sysFileInfo.getName())){
            fileName = sysFileInfo.getName();
        }
                HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(fileName.getBytes(),"iso-8859-1") ));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));


    }

}